package org.com.lcuiot.service;

import com.google.gson.Gson;
import org.com.lcuiot.common.TimeUtil;
import org.com.lcuiot.config.RedisStream;
import org.com.lcuiot.constant.LcuIotConst;
import org.com.lcuiot.database.dto.IotData;
import org.com.lcuiot.database.entity.Device;
import org.com.lcuiot.database.entity.DeviceData;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.util.Map;


/**
 * @author gaoge
 * @since 2022/10/26 22:18
 */
@Service
public class AcceptDataService {
    private static final Logger logger = LoggerFactory.getLogger(AcceptDataService.class);

    private final StringRedisTemplate redisTemplate;
    private RedisStream redisStream;
    private final DeviceDataService deviceDataService;
    private final DeviceService deviceService;


    @Autowired
    public AcceptDataService(StringRedisTemplate redisTemplate, RedisStream redisStream, DeviceDataService deviceDataService, DeviceService deviceService) {
        this.redisTemplate = redisTemplate;
        this.redisStream = redisStream;
        this.deviceDataService = deviceDataService;
        this.deviceService = deviceService;
    }

    public IotData save2RedisStream(IotData data) {
        Gson gson = new Gson();
        redisStream.add(LcuIotConst.IOT_STREAM, "data", gson.toJson(data));
        return data;
    }

    /**
     * @param data  将数据写入数据库
     */
    public void save2DB(Map<String, String> data) {
        try {
            logger.info("********* Insert DB {}", data);
            String dataModel = data.get("data");
            JSONObject map = new JSONObject(dataModel).getJSONObject("msg");
            int type = (int) map.get("type");
            logger.info("上传数据type类型" + type);
            // 数据点消息
            if (type == 1) {
                String devId = map.get("dev_id").toString();
                String dsId = (String) map.get("ds_id");
                Long dataAt = (Long) map.get("at");
                Object value = map.get("value");
                logger.info("数据点值：" + devId + ":" + dsId + ":" + dataAt + ":" + value);
                // 存入数据库
                DeviceData deviceData = new DeviceData();
                deviceData.setDevId(devId);
                deviceData.setDsId(dsId);
                deviceData.setDataAt(dataAt);
                deviceData.setDataValue(value.toString());
                deviceData.setCreateAt(TimeUtil.currentTimeMillis());
                deviceData.setUpdateAt(TimeUtil.currentTimeMillis());
                deviceDataService.addDeviceData(deviceData);
            }
            // 设备上下线消息
            if (type == 2) {
                String devId = map.get("dev_id").toString();
                int status = (int) map.get("status");
                logger.info("设备上下线值：" + devId + ":" + devId + ":" + status);
                Device device = new Device();
                device.setDevId(devId);
                device.setStatus(status);
                deviceService.patchDevice(device);
            }
        } catch (Exception e) {
            logger.error("将上传数据写入数据库发生异常：", e);
        }
    }
}
